<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            position: absolute;
            left: 0px;
            top: 300px;
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
    <button class="b1">800</button>
    <button class="b2">500</button>
    <div></div>
    <script>
        var b1 = document.querySelector('.b1');
        var b2 = document.querySelector('.b2');
        function animate(obj, target , fun){
            clearInterval(obj.timer);
            obj.timer = setInterval(function(){
                //目标值 - 当前位置
                // var step = Math.ceil((target - obj.offsetLeft) / 10);
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step); 
                if(obj.offsetLeft >= target && step > 0){
                    clearInterval(obj.timer);
                    if(fun){
                        fun();
                    }
                }else if(obj.offsetLeft <= target && step < 0){
                    clearInterval(obj.timer);
                    if(fun){
                        fun();
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            },30);
        }
        var div = document.querySelector('div');
        b1.addEventListener('click',function(){
            animate(div, 800);
        })
        b2.addEventListener('click',function(){
            animate(div, 500);
        })
    </script>
</body>
</html>